package com.pray.praymall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.pray.praymall.product.service.CategoryBrandRelationService;
import com.pray.praymall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pray.common.utils.PageUtils;
import com.pray.common.utils.Query;

import com.pray.praymall.product.dao.CategoryDao;
import com.pray.praymall.product.entity.CategoryEntity;
import com.pray.praymall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        // 2.1 找到所有的一级分类
        List<CategoryEntity> levelOneMenu = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(0L)
        ).peek(
                menu -> menu.setChildren(getChildren(menu, entities))
        ).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return levelOneMenu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> findCatelogPath(Long catalogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catalogId, paths);
        Collections.reverse(paths);
        return paths;
    }

    /**
     * 级联更新所有关联的数据
     * {@code @CacheEvict 失效模式}
     * {@code @Caching 同时进行多种缓存操作}
     * {@code @CacheEvict(value = "category", allEntries = true) 指定删除某个分区下所有数据}
     * 存储同一类型的数据吗，都可以指定同一个分区
     *
     * SpringCache的不足：
     *  1、读模式：
     *      缓存穿透：查询一个null数据。解决：缓存空数据；cache-null-values=true
     *      缓存击穿：大量并发进来同时查询一个正好过期的数据。解决：加锁；默认是无加锁的，sync=true(加锁，解决击穿)
     *      缓存雪崩：大量的key同时过期。解决：加随机时间。加上过期时间，time-to-live=3600000
     *  2、写模式（缓存与数据库一致）：
     *      读写加锁
     *      引入Canal，感知到MySql的更新去更新缓存
     *      读多写多，直接去数据库查询就行
     *  总结：常规数据（读多写少，即时性，一致性要求不高的数据），完全可以使用SpringCache；写模式（只要设置过期时间就行了）
     *      特殊数据：特殊设计
     *
     * @param category pojo
     */
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * {@code @Cacheable代表当前方法的结果需要缓存，如果缓存中有，方法不用调用，如果缓存中没有，会调用方法，最后将方法的返回结果放入缓存中
     * 每一个需要缓存的数据我们都需要指定要放到哪个名字的缓存。【缓存的分区（按照业务类型分）】
     * }
     *
     * @return
     */
    @Cacheable(value = {"category"}, key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        // 将多次查询变为1次
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = getParentCid(entities, 0L);
        Map<String, List<Catalog2Vo>> result = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // v是每一个一级分类，需要查找这个一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParentCid(entities, v.getCatId());

            // 将查出来的二级分类进行封装
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null && categoryEntities.size() > 0) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> catalog3Entities = getParentCid(entities, l2.getCatId());

                    if (catalog3Entities != null && catalog3Entities.size() > 0) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = catalog3Entities.stream()
                                .map(
                                        l3 -> new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())
                                ).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return result;
    }

    public Map<Long, List<Catalog2Vo>> getCatalogJsonByCache() {
        // 1、加入缓存，缓存中存的数据是json字符串

        /*
        1、空结果缓存，解决缓存穿透
        2、设置过期时间（加随机值）：解决缓存雪崩
        3、加锁：解决缓存击穿
         */
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(catalogJson)) {
            // 缓存中没有，查询数据库并放入缓存
            Map<Long, List<Catalog2Vo>> catalogJsonForDb = getCatalogJsonForDb();
            redisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(catalogJsonForDb));
            return catalogJsonForDb;
        }
        return JSON.parseObject(catalogJson, new TypeReference<Map<Long, List<Catalog2Vo>>>() {
        });
    }


    /**
     * 缓存里面的数据如何和数据库保持一致
     * 缓存数据一致性问题
     * 1、双写模式
     * 2、失效模式
     *
     * @return
     */
    public Map<Long, List<Catalog2Vo>> getCatalogJsonWithRedissonLock() {
        // 1、占分布式锁，去redis占坑
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<Long, List<Catalog2Vo>> jsonForDb;
        try {
            jsonForDb = getCatalogJsonForDb();
        } finally {
            lock.unlock();
        }
        return jsonForDb;
    }

    /**
     * 从数据库查询并封装分类数据
     *
     * @return 分类数据
     */
    public Map<Long, List<Catalog2Vo>> getCatalogJsonForDb() {
        // 将多次查询变为1次
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 1、查出所有一级分类
        List<CategoryEntity> level1Categorys = getParentCid(entities, 0L);
        Map<Long, List<Catalog2Vo>> result = level1Categorys.stream().collect(Collectors.toMap(CategoryEntity::getCatId, v -> {
            // v是每一个一级分类，需要查找这个一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParentCid(entities, v.getCatId());

            // 将查出来的二级分类进行封装
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null && categoryEntities.size() > 0) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> catalog3Entities = getParentCid(entities, l2.getCatId());

                    if (catalog3Entities != null && catalog3Entities.size() > 0) {
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = catalog3Entities.stream()
                                .map(
                                        l3 -> new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName())
                                ).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return result;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> entities, Long pId) {
        return entities.stream().filter(item -> item.getParentCid().equals(pId)).collect(Collectors.toList());
    }

    private void findParentPath(Long catalogId, List<Long> paths) {
        // 1.收集当前节点id
        paths.add(catalogId);
        CategoryEntity byId = this.getById(catalogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
    }

    /**
     * 递归查找给定菜单的子菜单
     *
     * @param root 给定的菜单
     * @param all  所有的菜单集合
     * @return 子菜单
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid().equals(root.getCatId())
        ).peek(
                categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, all))
        ).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}